package com.yiyuan.system.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.yiyuan.common.base.BaseAction;
import com.yiyuan.system.model.Employee;
import com.yiyuan.system.model.Organ;
import com.yiyuan.system.model.PriResource;
import com.yiyuan.system.model.Role;
import com.yiyuan.system.model.User;
import com.yiyuan.system.model.UserPri;
import com.yiyuan.system.model.UserRole;
import com.yiyuan.system.object.UserObject;
import com.yiyuan.system.service.ISystemService;

public class UserAction extends BaseAction {
    
    private static final long serialVersionUID = 1L;
    
    /* ************* 分页参数******************************************** */
    private String startrecord;
    private String endrecord;
    private String perpage;
    
    /* ************* form内容封装******************************************* */
    private String empId;
    private String userName;
    private String userId;
    private String password;
    private String deptId;
    private String selRoles;
    private String selPris;
    
    /* ************* 输出结果封装***************************************** */
    private User user;
    private List<User> list;
    private List<Role> roleUsedList;
    private List<Role> roleAllList;
    private List<PriResource> priUsedList;
    private List<PriResource> priAllList;
    private List<Organ> deptList;
    private List<Employee> empList;
    
    /* ************* 各功能函数******************************************* */
    // 资源引用
    @Resource
    private ISystemService systemService;
    
    // 进入用户主页
    public String index() {
        //加载部门列表
        deptList = this.systemService.findOrgList();
        return "toMain";
    }
    
    // 保存用户
    public void save() {
        User user = null;
        
        if (selRoles != null && !selRoles.equals("")) {
            selRoles = selRoles.substring(1);
        }
        if (selPris != null && !selPris.equals("")) {
            selPris = selPris.substring(1);
        }
        
        String userRoles[] = selRoles.split(",");
        String userPris[] = selPris.split(",");
        
        if (this.userId != null && !this.userId.equals("")) {// 修改
            user = this.systemService.getUser(Integer.valueOf(this.userId));
            user.setUserName(this.userName);
            user.setEmpId(Integer.valueOf(this.empId));
            user.setPassword(this.password);
            user.setUserRoles(userRoles);
            user.setUserPris(userPris);
            this.systemService.updateUser(user);
        } else {// 新增
            user = new User();
            user.setUserName(this.userName);
            user.setPassword(this.password);
            user.setEmpId(Integer.valueOf(this.empId));
            user.setUserRoles(userRoles);
            user.setUserPris(userPris);
            this.systemService.addUser(user);
        }
        try {
            ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
            ServletActionContext.getResponse().setContentType("text/xml; charset=utf-8");
            ServletActionContext.getResponse().getWriter().println("1");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 用户分页显示
    @SuppressWarnings("unchecked")
    public void listPage() {
        int start = 1;
        int end = 100;
        
        // 三个内置参数
        if (this.getStartrecord() != null && this.getEndrecord() != null && this.getPerpage() != null) {
            start = Integer.parseInt(this.getStartrecord());
            end = Integer.parseInt(this.getEndrecord());
        }
        
        Integer pDeptId = null;
        Integer pEmpId = null;
        if (this.deptId != null && !this.deptId.equals("")) {
            pDeptId = Integer.valueOf(this.deptId);
        }
        if (this.empId != null && !this.empId.equals("")) {
            pEmpId = Integer.valueOf(this.empId);
        }
        int totalRecord = systemService.getUserPageCount(pDeptId, pEmpId);
        list = systemService.findUserList(start, end, pDeptId, pEmpId);
        // try{
        // Thread.sleep(2000);
        // }catch(Exception e){
        //			
        // }
        Map map = new HashMap();
        map.put("list", list);
        map.put("totalRecord", totalRecord);
        JSONObject jso = new JSONObject(map);
        
        try {
            ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
            ServletActionContext.getResponse().setContentType("text/xml; charset=utf-8");
            
            ServletActionContext.getResponse().getWriter().print(jso.toString());
        } catch (Exception e) {
            
        }
    }
    
    // 删除用户
    public void del() {
        String ret = null;
        try {
            this.systemService.deleteUser(Integer.valueOf(this.userId));
            ret = "delete";
        } catch (Exception e) {
            ret = "error";
        }
        
        try {
            ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
            ServletActionContext.getResponse().setContentType("text/xml; charset=utf-8");
            ServletActionContext.getResponse().getWriter().print(ret);
        } catch (Exception e) {
            
        }
        
    }
    
    // 查看用户详细
    public String view() {
        if (this.userId != null && !this.userId.equals("")) {
            roleUsedList = new ArrayList<Role>();
            roleAllList = new ArrayList<Role>();
            Role role = null;
            UserRole userRole = null;
            
            priUsedList = new ArrayList<PriResource>();
            priAllList = new ArrayList<PriResource>();
            PriResource pri = null;
            UserPri userPri = null;
            
            boolean flag = false;
            // 加载用户对象
            this.user = this.systemService.getUser(Integer.valueOf(userId));
            //加载员工对象
            Employee employee = this.systemService.loadEmp(user.getEmpId());
            this.deptId = employee.getDeptId().toString();
            this.empId = employee.getEmpId().toString();
            
            // 加载用户角色
            List<UserRole> curList = this.systemService.findUserRoleListByUserId(Integer.valueOf(userId));
            // 加载全部角色列表,并且封装到两个list中
            List<Role> allList = this.systemService.findRoleList();
            for (int i = 0; i < allList.size(); i++) {
                role = allList.get(i);
                for (int j = 0; j < curList.size(); j++) {
                    userRole = curList.get(j);
                    if (role.getRoleId().intValue() == userRole.getRoleId().intValue()) {
                        roleUsedList.add(role);
                        flag = true;
                    }
                }
                if (!flag) {
                    roleAllList.add(role);
                }
                flag = false;
            }
            // 加载用户权限
            List<UserPri> curPriList = this.systemService.findUserPriListByUserId(Integer.valueOf(userId));
            // 加载全部权限列表，并且封装到两个list中
            List<PriResource> priList = this.systemService.findPriResList();
            for (int i = 0; i < priList.size(); i++) {
                pri = priList.get(i);
                for (int j = 0; j < curPriList.size(); j++) {
                    userPri = curPriList.get(j);
                    if (userPri.getPriId().intValue() == pri.getResId().intValue()) {
                        priUsedList.add(pri);
                        flag = true;
                    }
                }
                if (!flag) {
                    priAllList.add(pri);
                }
                flag = false;
            }
        }
        //加载部门列表
        deptList = this.systemService.findOrgList();
        //加载人员列表
        empList = systemService.getEmpListByDeptId(Integer.valueOf(deptId));
        
        return "toView";
        
    }
    
    // 进入用户增加页面
    public String add() {
        // 加载全部权限列表
        this.priAllList = this.systemService.findPriResList();
        // 加载全部角色列表
        this.roleAllList = this.systemService.findRoleList();
        //加载部门列表
        deptList = this.systemService.findOrgList();
        //加载人员空列表
        empList = new ArrayList<Employee>();
        return "toAdd";
    }
    
    //根据部门查询用户
    @SuppressWarnings("unchecked")
    public void getUserList() throws IOException {
        
        List<UserObject> userList = systemService.getUserList(deptId);
        Map map = new HashMap();
        map.put("list", userList);
        
        JSONObject jso = new JSONObject(map);
        
        ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
        ServletActionContext.getResponse().setContentType("text/xml; charset=utf-8");
        ServletActionContext.getResponse().getWriter().print(jso.toString());
        
    }
    
    /* ********************************************************************** */
    
    public String getEmpId() {
        return empId;
    }
    
    public void setEmpId(String empId) {
        this.empId = empId;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getUserId() {
        return userId;
    }
    
    public void setUserId(String userId) {
        this.userId = userId;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getDeptId() {
        return deptId;
    }
    
    public void setDeptId(String deptId) {
        this.deptId = deptId;
    }
    
    public String getStartrecord() {
        return startrecord;
    }
    
    public void setStartrecord(String startrecord) {
        this.startrecord = startrecord;
    }
    
    public String getEndrecord() {
        return endrecord;
    }
    
    public void setEndrecord(String endrecord) {
        this.endrecord = endrecord;
    }
    
    public String getPerpage() {
        return perpage;
    }
    
    public void setPerpage(String perpage) {
        this.perpage = perpage;
    }
    
    public List<User> getList() {
        return this.list;
    }
    
    public User getUser() {
        return user;
    }
    
    public void setUser(User user) {
        this.user = user;
    }
    
    public List<Role> getRoleUsedList() {
        return roleUsedList;
    }
    
    public List<Role> getRoleAllList() {
        return roleAllList;
    }
    
    public List<PriResource> getPriUsedList() {
        return priUsedList;
    }
    
    public List<PriResource> getPriAllList() {
        return priAllList;
    }
    
    public String getSelRoles() {
        return selRoles;
    }
    
    public void setSelRoles(String selRoles) {
        this.selRoles = selRoles;
    }
    
    public String getSelPris() {
        return selPris;
    }
    
    public void setSelPris(String selPris) {
        this.selPris = selPris;
    }
    
    public List<Organ> getDeptList() {
        return deptList;
    }
    
    public void setDeptList(List<Organ> deptList) {
        this.deptList = deptList;
    }
    
    public List<Employee> getEmpList() {
        return empList;
    }
    
    public void setEmpList(List<Employee> empList) {
        this.empList = empList;
    }
}
